<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>高级秒表应用</title>
    <!-- 本地引用Tailwind CSS -->
    <script src="assets/js/tailwind.min.js"></script>
    <!-- 本地引用Chart.js -->
    <script src="assets/js/chart.umd.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#6366F1',
                        accent: '#EC4899',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .timer-display {
                font-variant-numeric: tabular-nums;
            }
            .history-item-enter {
                opacity: 0;
                transform: translateY(10px);
            }
            .history-item-enter-active {
                opacity: 1;
                transform: translateY(0);
                transition: opacity 300ms, transform 300ms;
            }
            .glass-effect {
                backdrop-filter: blur(10px);
                background-color: rgba(255, 255, 255, 0.7);
            }
            .pulse-animation {
                animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
            }
            @keyframes pulse {
                0%, 100% {
                    opacity: 1;
                }
                50% {
                    opacity: 0.7;
                }
            }
        }
    </style>
    <!-- 预定义Tailwind工具类 -->
    <style>
        .bg-gradient-to-br {
            background-image: linear-gradient(to bottom right, var(--tw-gradient-stops));
        }
        .from-blue-50 {
            --tw-gradient-from: #EFF6FF;
            --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(239, 246, 255, 0));
        }
        .to-indigo-100 {
            --tw-gradient-to: #E0E7FF;
        }
        .shadow-xl {
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        .hover:shadow-2xl:hover {
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
        }
        .transition-all {
            transition-property: all;
            transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
            transition-duration: 150ms;
        }
        .duration-300 {
            transition-duration: 300ms;
        }
        .hover:-translate-y-1:hover {
            transform: translateY(-0.25rem);
        }
        .grid-cols-1 {
            grid-template-columns: repeat(1, minmax(0, 1fr));
        }
        .md:grid-cols-3 {
            grid-template-columns: repeat(3, minmax(0, 1fr));
        }
    </style>
</head>
<body class="bg-gradient-to-br from-blue-50 to-indigo-100 min-h-screen font-sans">
    <div class="container mx-auto px-4 py-8 max-w-4xl">
        <!-- 主要内容区域 -->
        <main class="bg-white rounded-2xl shadow-xl overflow-hidden transition-all duration-300 hover:shadow-2xl">
            <!-- 模式切换 -->
            <div class="bg-gray-50 border-b border-gray-200">
                <div class="flex">
                    <button id="mode1Btn" class="flex-1 py-4 px-6 text-center font-medium text-primary border-b-2 border-primary transition-all duration-200 hover:bg-gray-100">
                        🔄 类型1：每次从0开始
                    </button>
                    <button id="mode2Btn" class="flex-1 py-4 px-6 text-center font-medium text-gray-500 transition-all duration-200 hover:bg-gray-100">
                        ▶️ 类型2：继续计时
                    </button>
                </div>
            </div>

            <!-- 计时器显示 -->
            <div class="p-8 flex flex-col items-center">
                <!-- 快捷键提示 -->
                <p class="text-gray-500 text-lg mt-2">
                    <kbd class="px-2 py-1 bg-gray-100 text-gray-700 rounded text-lg">空格</kbd> 开始/记录 • 
                    <kbd class="px-2 py-1 bg-gray-100 text-gray-700 rounded text-lg">P</kbd> 暂停 • 
                    <kbd class="px-2 py-1 bg-gray-100 text-gray-700 rounded text-lg">R</kbd> 重置
                </p>
                
                <div class="timer-display text-[clamp(2rem,8vw,6rem)] font-mono font-bold text-dark mb-6 tracking-wider">00:00:00</div>

                <!-- 控制按钮 -->
                <div class="flex flex-wrap justify-center gap-4 mb-8">
                    <button id="startBtn" class="px-8 py-3 bg-primary hover:bg-primary/90 text-white font-semibold rounded-full shadow-lg hover:shadow-xl transition-all duration-200 transform hover:-translate-y-1 flex items-center">
                        ▶️ 开始
                    </button>
                    <button id="pauseBtn" class="px-8 py-3 bg-gray-600 hover:bg-gray-700 text-white font-semibold rounded-full shadow-lg hover:shadow-xl transition-all duration-200 transform hover:-translate-y-1 flex items-center hidden">
                        ⏸️ 暂停
                    </button>
                    <button id="resetBtn" class="px-8 py-3 bg-gray-200 hover:bg-gray-300 text-gray-700 font-semibold rounded-full shadow-lg hover:shadow-xl transition-all duration-200 transform hover:-translate-y-1 flex items-center">
                        🔄 重置
                    </button>
                    <button id="recordBtn" class="px-8 py-3 bg-accent hover:bg-accent/90 text-white font-semibold rounded-full shadow-lg hover:shadow-xl transition-all duration-200 transform hover:-translate-y-1 flex items-center">
                        ➕ 记录
                    </button>
                </div>

                <!-- 标签选择器和自定义编号区域 -->
                <div class="w-full grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
                    <!-- 标签选择器 -->
                    <div class="bg-gray-50 p-4 rounded-lg border border-gray-200 md:col-span-2">
                        <h3 class="font-medium text-gray-800 mb-2 flex items-center">
                            <i class="fa fa-tags mr-2"></i> 标签管理
                        </h3>
                        <div class="flex flex-wrap gap-2 mb-3" id="tagList">
                            <span class="px-3 py-1 bg-primary/10 text-primary rounded-full text-sm cursor-pointer tag-selected">默认</span>
                            <span class="px-3 py-1 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-full text-sm cursor-pointer transition-colors duration-200">刷题</span>
                            <span class="px-3 py-1 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-full text-sm cursor-pointer transition-colors duration-200">跑步</span>
                            <span class="px-3 py-1 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-full text-sm cursor-pointer transition-colors duration-200">A</span>
                            <span class="px-3 py-1 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-full text-sm cursor-pointer transition-colors duration-200">B</span>
                            <span class="px-3 py-1 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-full text-sm cursor-pointer transition-colors duration-200">C</span>
                            <span class="px-3 py-1 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-full text-sm cursor-pointer transition-colors duration-200">D</span>                        
                        </div>
                        <div class="flex gap-2">
                            <input type="text" id="newTagInput" placeholder="输入自定义标签..." class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                            <button id="addTagBtn" class="px-4 py-2 bg-secondary hover:bg-secondary/90 text-white rounded-lg transition-all duration-200">
                                ➕
                            </button>
                        </div>
                    </div>

                    <!-- 自定义备注 -->
                    <div class="bg-gray-50 p-4 rounded-lg border border-gray-200 md:col-span-1">
                        <h3 class="font-medium text-gray-800 mb-2 flex items-center">
                            <i class="fa fa-list-ol mr-2"></i> 自增数字
                        </h3>
                        <div class="flex gap-2">
                            <input type="number" id="startNumberInput" min="1" value="1" class="flex-1 px-1 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                            <button id="applyStartNumberBtn" class="px-2 py-1 bg-primary hover:bg-primary/90 text-white rounded-lg transition-all duration-200">
                                应用
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 历史记录区域 -->
            <div class="bg-gray-50 p-6 border-t border-gray-200">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-bold text-gray-800 flex items-center">
                        📜 历史记录
                    </h2>
                    <div class="flex gap-2">
                        <button id="exportBtn" class="px-3 py-1 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-lg text-sm transition-all duration-200 flex items-center">
                            💾 导出
                        </button>
                        <button id="clearBtn" class="px-3 py-1 bg-red-100 hover:bg-red-200 text-red-600 rounded-lg text-sm transition-all duration-200 flex items-center">
                            🗑️ 清空
                        </button>
                    </div>
                </div>
                
                <!-- 历史记录表格 -->
                <div class="overflow-x-auto">
                    <table class="min-w-full bg-white rounded-lg shadow-sm">
                        <thead>
                            <tr class="bg-gray-100 text-left text-base font-medium text-gray-500 uppercase tracking-wider">
                                <th class="px-4 py-3 rounded-tl-lg">序号</th>
                                <th class="px-4 py-3">标签</th>
                                <th class="px-4 py-3">时间</th>
                                <th class="px-4 py-3 rounded-tr-lg">操作</th>
                            </tr>
                        </thead>
                        <tbody id="historyTableBody" class="divide-y divide-gray-200">
                            <!-- 历史记录将通过JavaScript动态添加 -->
                            <tr class="text-center text-gray-500">
                                <td colspan="4" class="px-4 py-8">暂无记录</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                
                <!-- 统计信息 -->
                <div class="mt-6 p-4 bg-white rounded-lg shadow-sm">
                    <h3 class="font-semibold text-gray-700 mb-2">📊 统计信息</h3>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div class="text-center">
                            <p class="text-sm text-gray-500">记录总数</p>
                            <p id="totalRecords" class="text-2xl font-bold text-gray-800">0</p>
                        </div>
                        <div class="text-center">
                            <p class="text-sm text-gray-500">总时长</p>
                            <p id="totalTime" class="text-2xl font-bold text-gray-800">00:00:00</p>
                        </div>
                        <div class="text-center">
                            <p class="text-sm text-gray-500">平均时长</p>
                            <p id="averageTime" class="text-2xl font-bold text-gray-800">00:00:00</p>
                        </div>
                    </div>
                </div>
                
                <!-- 数据可视化 -->
                <div class="mt-6 p-4 bg-white rounded-lg shadow-sm">
                    <h3 class="font-semibold text-gray-700 mb-4">📈 时长分布</h3>
                    <div class="h-64">
                        <canvas id="timeChart"></canvas>
                    </div>
                </div>
            </div>
        </main>

        <!-- 页脚 -->
        <footer class="mt-12 text-center text-gray-500 text-sm">
            <p>秒表 © 2025 | 所有计时数据保存在本地浏览器中</p>
        </footer>
    </div>

    <script>
        // 全局变量
        let timer = {
            startTime: null,
            accumulatedTime: 0,
            interval: null,
            isRunning: false,
            mode: 1, // 1: 类型1(每次从0开始), 2: 类型2(继续计时)
            currentTag: '默认'
        };
        
        let records = JSON.parse(localStorage.getItem('stopwatchRecords')) || [];
        let timeChart = null;
        let startNumber = parseInt(localStorage.getItem('stopwatchStartNumber')) || 1;
        
        // DOM 元素
        let timerDisplay, startBtn, pauseBtn, resetBtn, recordBtn, mode1Btn, mode2Btn, historyTableBody, newTagInput, addTagBtn, tagList, clearBtn, exportBtn, totalRecords, totalTime, averageTime, timeChartCanvas, startNumberInput, applyStartNumberBtn;
        
        // 初始化应用
        document.addEventListener('DOMContentLoaded', function() {
            // 获取DOM元素
            timerDisplay = document.querySelector('.timer-display');
            startBtn = document.getElementById('startBtn');
            pauseBtn = document.getElementById('pauseBtn');
            resetBtn = document.getElementById('resetBtn');
            recordBtn = document.getElementById('recordBtn');
            mode1Btn = document.getElementById('mode1Btn');
            mode2Btn = document.getElementById('mode2Btn');
            historyTableBody = document.getElementById('historyTableBody');
            newTagInput = document.getElementById('newTagInput');
            addTagBtn = document.getElementById('addTagBtn');
            tagList = document.getElementById('tagList');
            clearBtn = document.getElementById('clearBtn');
            exportBtn = document.getElementById('exportBtn');
            totalRecords = document.getElementById('totalRecords');
            totalTime = document.getElementById('totalTime');
            averageTime = document.getElementById('averageTime');
            timeChartCanvas = document.getElementById('timeChart');
            startNumberInput = document.getElementById('startNumberInput');
            applyStartNumberBtn = document.getElementById('applyStartNumberBtn');
            
            // 设置起始编号输入框的值
            startNumberInput.value = startNumber;
            
            // 初始化应用状态
            updateHistoryTable();
            updateStatistics();
            initChart();
            
            // 绑定事件监听器
            startBtn.addEventListener('click', startTimer);
            pauseBtn.addEventListener('click', pauseTimer);
            resetBtn.addEventListener('click', resetTimer);
            recordBtn.addEventListener('click', recordTime);
            mode1Btn.addEventListener('click', switchToMode1);
            mode2Btn.addEventListener('click', switchToMode2);
            addTagBtn.addEventListener('click', addNewTag);
            clearBtn.addEventListener('click', clearAllRecords);
            exportBtn.addEventListener('click', exportRecords);
            applyStartNumberBtn.addEventListener('click', applyStartNumber);
            
            // 回车键添加新标签
            newTagInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    addNewTag();
                }
            });
            
            // 点击标签选择
            tagList.addEventListener('click', function(e) {
                if (e.target.tagName === 'SPAN') {
                    selectTag(e.target.textContent);
                }
            });
            
            // 为预设标签添加点击事件
            Array.from(tagList.querySelectorAll('span')).forEach(tag => {
                tag.addEventListener('click', function() {
                    selectTag(tag.textContent);
                });
            });
            
            // 窗口大小变化时更新图表
            window.addEventListener('resize', function() {
                if (timeChart) {
                    timeChart.resize();
                }
            });
            
            // 窗口关闭前保存记录
            window.addEventListener('beforeunload', saveRecords);
            
            // 绑定键盘事件
            document.addEventListener('keydown', handleKeyPress);
        });
        
        // 处理键盘快捷键
        function handleKeyPress(e) {
            // 忽略输入框中的按键
            if (e.target.tagName === 'INPUT') return;
            
            switch(e.key.toLowerCase()) {
                case ' ': // 空格键
                    e.preventDefault(); // 防止页面滚动
                    if (timer.isRunning) {
                        recordTime();
                    } else {
                        startTimer();
                    }
                    break;
                    
                case 'p': // P键 - 暂停
                    if (timer.isRunning) {
                        pauseTimer();
                    }
                    break;
                    
                case 'r': // R键 - 重置
                    resetTimer();
                    break;
            }
        }
        
        // 格式化时间显示 (毫秒 -> HH:MM:SS)
        function formatTime(milliseconds) {
            const totalSeconds = Math.floor(milliseconds / 1000);
            const hours = Math.floor(totalSeconds / 3600);
            const minutes = Math.floor((totalSeconds % 3600) / 60);
            const seconds = totalSeconds % 60;
            
            return [
                hours.toString().padStart(2, '0'),
                minutes.toString().padStart(2, '0'),
                seconds.toString().padStart(2, '0')
            ].join(':');
        }
        
        // 更新计时器显示
        function updateTimerDisplay() {
            let currentTime;
            if (timer.isRunning) {
                currentTime = timer.accumulatedTime + (Date.now() - timer.startTime);
            } else {
                currentTime = timer.accumulatedTime;
            }
            
            timerDisplay.textContent = formatTime(currentTime);
        }
        
        // 开始计时器
        function startTimer() {
            if (!timer.isRunning) {
                if (timer.mode === 1 && timer.accumulatedTime > 0) {
                    // 类型1模式下，如果已经有累积时间，则重置为0
                    timer.accumulatedTime = 0;
                }
                
                timer.startTime = Date.now();
                timer.isRunning = true;
                timer.interval = setInterval(updateTimerDisplay, 100);
                
                // 更新按钮状态
                startBtn.classList.add('hidden');
                pauseBtn.classList.remove('hidden');
                
                // 添加动画效果
                timerDisplay.classList.add('text-primary');
                startBtn.classList.add('pulse-animation');
            }
        }
        
        // 暂停计时器
        function pauseTimer() {
            if (timer.isRunning) {
                timer.accumulatedTime += Date.now() - timer.startTime;
                timer.isRunning = false;
                clearInterval(timer.interval);
                
                // 更新按钮状态
                pauseBtn.classList.add('hidden');
                startBtn.classList.remove('hidden');
                
                // 移除动画效果
                timerDisplay.classList.remove('text-primary');
                startBtn.classList.remove('pulse-animation');
            }
        }
        
        // 重置计时器
        function resetTimer() {
            pauseTimer();
            timer.accumulatedTime = 0;
            updateTimerDisplay();
        }
        
        // 记录当前时间
        function recordTime() {
            if (timer.isRunning && timer.mode === 1) {
                // 在类型1模式下记录时，暂停计时器
                pauseTimer();
            }
            
            const time = timer.isRunning 
                ? timer.accumulatedTime + (Date.now() - timer.startTime) 
                : timer.accumulatedTime;
            
            if (time === 0) return; // 不记录0时间
            
            const record = {
                id: Date.now(),
                time,
                formattedTime: formatTime(time),
                tag: timer.currentTag,
                timestamp: new Date().toLocaleString(),
                customNumber: startNumber // 保存自定义编号
            };
            
            records.unshift(record); // 添加到记录数组开头
            saveRecords();
            updateHistoryTable();
            updateStatistics();
            updateChart();
            
            // 更新起始编号
            startNumber++;
            localStorage.setItem('stopwatchStartNumber', startNumber);
            startNumberInput.value = startNumber;
            
            if (timer.mode === 1) {
                // 在类型1模式下记录后，重置计时器
                resetTimer();
            }
            
            // 添加记录动画
            const firstRow = historyTableBody.querySelector('tr');
            if (firstRow) {
                firstRow.classList.add('bg-primary/5');
                setTimeout(() => {
                    firstRow.classList.remove('bg-primary/5');
                }, 1000);
            }
        }
        
        // 保存记录到本地存储
        function saveRecords() {
            localStorage.setItem('stopwatchRecords', JSON.stringify(records));
        }
        
        // 更新历史记录表格
        function updateHistoryTable() {
            if (records.length === 0) {
                historyTableBody.innerHTML = `
                    <tr class="text-center text-gray-500">
                        <td colspan="4" class="px-4 py-8">暂无记录</td>
                    </tr>
                `;
                return;
            }
            
            historyTableBody.innerHTML = '';
            records.forEach((record, index) => {
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50 transition-colors duration-150';
                row.innerHTML = `
                    <td class="px-4 py-3 text-gray-800">${index + 1}</td>
                    <td class="px-4 py-3">
                        <span class="px-2 py-1 bg-primary/10 text-primary rounded-full text-base">${record.tag}</span>
                        <span class="ml-2 text-base text-gray-500">(${record.customNumber})</span>
                    </td>
                    <td class="px-4 py-3 font-mono text-base">${record.formattedTime}</td>
                    <td class="px-4 py-3">
                        <button class="text-red-500 hover:text-red-700 transition-colors duration-150 delete-record" data-id="${record.id}">
                            ❌
                        </button>
                    </td>
                `;
                historyTableBody.appendChild(row);
            });
            
            // 添加删除记录事件监听
            document.querySelectorAll('.delete-record').forEach(btn => {
                btn.addEventListener('click', function() {
                    const id = parseInt(this.getAttribute('data-id'));
                    records = records.filter(record => record.id !== id);
                    saveRecords();
                    updateHistoryTable();
                    updateStatistics();
                    updateChart();
                });
            });
        }
        
        // 更新统计信息
        function updateStatistics() {
            const count = records.length;
            totalRecords.textContent = count;
            
            if (count === 0) {
                totalTime.textContent = '00:00:00';
                averageTime.textContent = '00:00:00';
                return;
            }
            
            const totalMs = records.reduce((sum, record) => sum + record.time, 0);
            totalTime.textContent = formatTime(totalMs);
            
            const avgMs = totalMs / count;
            averageTime.textContent = formatTime(avgMs);
        }
        
        // 初始化图表
        function initChart() {
            if (timeChart) {
                timeChart.destroy();
            }
            
            timeChart = new Chart(timeChartCanvas, {
                type: 'bar',
                data: {
                    labels: records.slice(0, 10).map(record => `记录${record.customNumber}`),
                    datasets: [{
                        label: '时长(秒)',
                        data: records.slice(0, 10).map(record => record.time / 1000),
                        backgroundColor: 'rgba(59, 130, 246, 0.7)',
                        borderColor: 'rgba(59, 130, 246, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: '秒'
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
        }
        
        // 更新图表
        function updateChart() {
            if (!timeChart) {
                initChart();
                return;
            }
            
            timeChart.data.labels = records.slice(0, 10).map(record => `记录${record.customNumber}`);
            timeChart.data.datasets[0].data = records.slice(0, 10).map(record => record.time / 1000);
            timeChart.update();
        }
        
        // 切换到类型1模式
        function switchToMode1() {
            if (timer.mode !== 1) {
                timer.mode = 1;
                mode1Btn.classList.add('text-primary', 'border-b-2', 'border-primary');
                mode1Btn.classList.remove('text-gray-500');
                mode2Btn.classList.remove('text-primary', 'border-b-2', 'border-primary');
                mode2Btn.classList.add('text-gray-500');
                
                // 重置计时器
                resetTimer();
            }
        }
        
        // 切换到类型2模式
        function switchToMode2() {
            if (timer.mode !== 2) {
                timer.mode = 2;
                mode2Btn.classList.add('text-primary', 'border-b-2', 'border-primary');
                mode2Btn.classList.remove('text-gray-500');
                mode1Btn.classList.remove('text-primary', 'border-b-2', 'border-primary');
                mode1Btn.classList.add('text-gray-500');
                
                // 重置计时器
                resetTimer();
            }
        }
        
        // 添加新标签
        function addNewTag() {
            const tagName = newTagInput.value.trim();
            if (tagName && !hasTag(tagName)) {
                // 创建新标签元素
                const tagElement = document.createElement('span');
                tagElement.className = 'px-3 py-1 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-full text-sm cursor-pointer transition-colors duration-200';
                tagElement.textContent = tagName;
                
                // 添加点击事件
                tagElement.addEventListener('click', function() {
                    selectTag(tagName);
                });
                
                // 添加到标签列表
                tagList.appendChild(tagElement);
                
                // 选中新标签
                selectTag(tagName);
                
                // 清空输入框
                newTagInput.value = '';
            } else {
                // 输入为空或标签已存在，给出反馈
                newTagInput.classList.add('border-red-500');
                setTimeout(() => {
                    newTagInput.classList.remove('border-red-500');
                }, 1000);
            }
        }
        
        // 检查标签是否存在
        function hasTag(tagName) {
            const tags = Array.from(tagList.querySelectorAll('span'));
            return tags.some(tag => tag.textContent === tagName);
        }
        
        // 选择标签
        function selectTag(tagName) {
            // 移除所有标签的选中状态
            Array.from(tagList.querySelectorAll('span')).forEach(tag => {
                tag.classList.remove('bg-primary/10', 'text-primary', 'tag-selected');
                tag.classList.add('bg-gray-200', 'text-gray-700');
            });
            
            // 设置当前标签
            timer.currentTag = tagName;
            
            // 添加选中状态到当前标签
            const selectedTag = Array.from(tagList.querySelectorAll('span')).find(tag => tag.textContent === tagName);
            if (selectedTag) {
                selectedTag.classList.remove('bg-gray-200', 'text-gray-700');
                selectedTag.classList.add('bg-primary/10', 'text-primary', 'tag-selected');
            }
        }
        
        // 清空所有记录
        function clearAllRecords() {
            if (records.length > 0 && confirm('确定要清空所有记录吗？此操作不可恢复。')) {
                records = [];
                saveRecords();
                updateHistoryTable();
                updateStatistics();
                updateChart();
                
                // 添加清空动画
                historyTableBody.classList.add('animate-pulse');
                setTimeout(() => {
                    historyTableBody.classList.remove('animate-pulse');
                }, 1000);
            }
        }
        
        // 导出记录
        function exportRecords() {
            if (records.length === 0) {
                alert('没有记录可导出');
                return;
            }
            
            // 创建CSV内容
            let csvContent = "自定义编号,序号,时间,标签,记录时间\n";
            records.forEach((record, index) => {
                csvContent += `${record.customNumber},${index + 1},${record.formattedTime},${record.tag},${record.timestamp}\n`;
            });
            
            // 创建Blob并下载
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            
            link.setAttribute('href', url);
            link.setAttribute('download', `秒表记录_${new Date().toISOString().slice(0, 10)}.csv`);
            link.style.visibility = 'hidden';
            
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        
        // 应用起始编号
        function applyStartNumber() {
            const newStartNumber = parseInt(startNumberInput.value);
            if (!isNaN(newStartNumber) && newStartNumber >= 1) {
                startNumber = newStartNumber;
                localStorage.setItem('stopwatchStartNumber', startNumber);
                updateHistoryTable();
                updateChart();
                
                // 添加成功反馈
                applyStartNumberBtn.classList.add('bg-green-600');
                setTimeout(() => {
                    applyStartNumberBtn.classList.remove('bg-green-600');
                }, 1000);
            } else {
                // 输入无效，给出反馈
                startNumberInput.classList.add('border-red-500');
                setTimeout(() => {
                    startNumberInput.classList.remove('border-red-500');
                }, 1000);
            }
        }
    </script>
</body>
</html>